{% extends 'base.html' %}
{% load staticfiles %}
{% block styles %}
    <style type="text/css" media="screen">
        #editor, #codedetail {
            font-size: 15px;
            width: 49%;
            height: 500px;

        }

        #editor {
            float: left;
        }

        .row {
            height: 30px;
        }

        #codedetail {
            width: 50%;
            float: right;
        }

        .para, .invali, .netline, .codelog {
            height: 125px;
            margin-top: 30px;
        }

        .hisback, .compile, .runback {
            height: 30px;
        }

        .runback {
            background-color: #3a8ace;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="container" style="background-color: black">
        <div class="row">
            <div class="col-md-6 text-title">策略名称</div>
            <div class="col-md-6">
                {#                <button class="hisback">历史回测</button>#}
                {#                <button class="compile">编译策略</button>#}
                <button class="runback text-title" onclick="runback_now({{ stgid }})">运行回测</button>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <button class="thmd text-title" onclick="theme_change(this, 1)">白色主题</button>
                <button class="thmd theme-active text-title" onclick="theme_change(this, 2)">黑色主题</button>
            </div>
            <div id="stg-code" class="col-md-6" style="display: none">{{ stgfile }}</div>
        </div>
        <div class="codeditor">
            <!--编写策略代码-->
            <div id="editor">
            </div>
            <div id="codedetail">
                <div class="date">
                    <span class="text-title">日期</span>
                    <input placeholder="yyyy-mm-dd" class="date-input" type="text"
                           id="start_date">
                    <span class="text-title">至</span>
                    <input placeholder="yyyy-mm-dd" class="date-input" type="text"
                           id="end_date">
                </div>
                <div class="box-header with-border">
                    <h4 class="box-title">收益概览</h4>
                    <div>
                        <p></p>
                        <table class="table">
                            <tbody>
                            <tr class="back-detail">
                                <th data-align="center">起始日期</th>
                                <th data-align="center">结束日期</th>
                                <th data-align="center">回测收益</th>
                                <th data-align="center">回测年化收益</th>
                                <th data-align="center">夏普率</th>
                                <th data-align="center">索提诺比率</th>
                                <th data-align="center">calmar比率</th>
                                <th data-align="center">年化波动率</th>
                                <th data-align="center">最大回撤</th>
                            </tr>
                            <tr>
                                <td data-align="center" id="st_date"></td>
                                <td data-align="center" id="en_date"></td>
                                <td data-align="center" id="total_return"></td>
                                <td data-align="center" id="annual_return"></td>
                                <td data-align="center" id="sharpe_ratio"></td>
                                <td data-align="center" id="sortino_ratio"></td>
                                <td data-align="center" id="calmar_ratio"></td>
                                <td data-align="center" id="annual_volatility"></td>
                                <td data-align="center" id="max_draw_down"></td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="box-header with-border">
                    <h4 class="box-title">净值曲线</h4>
                </div>
                <div class="box-body " style="padding: 10px; height:350px;">
                    <div id="cumulativereturns" style="height: 230px; width: 100%;">
                    </div>
                </div>
            </div>
        </div>
    </div>


{% endblock %}
{% block scripts %}
    <script src="http://cdn.bootcss.com/ace/1.2.4/ace.js"></script>
    <script src="http://cdn.bootcss.com/ace/1.2.4/ext-language_tools.js"></script>
    <script>

        //日期选择器
        var start_date = $("#start_date")
        var end_date = $("#end_date")
        var period_get = null
        ace.require('ace/ext/language_tools');
        var editor = ace.edit("editor");
        {#var codedetail = ace.edit("codedetail")#}
        editor.setTheme("ace/theme/monokai"); //github是白色主题，//monokai是黑色主题
        {#codedetail.setTheme("ace/theme/github"); //github是白色主题，//monokai是黑色主题#}
        editor.session.setMode("ace/mode/python");
        editor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
        });
        editor.on("change", function (e) {
            editor.execCommand("startAutocomplete");
        })
        {#codedetail.session.setMode("ace/mode/python");#}

        //页面初始化时加载策略代码
        $(function () {
            var stgcode_obj = $("#stg-code").text()
            if (stgcode_obj){
                editor.setValue(stgcode_obj)
            } else {
                editor.setValue(order_stg_cdh)
            }

        })


        function theme_change(ths, n) {
            $(ths).parents(".col-md-6").children().removeClass("theme-active")
            $(ths).addClass("theme-active")
            switch (n) {
                case 1:
                    editor.setTheme("ace/theme/github");
                    break;
                case 2:
                    editor.setTheme("ace/theme/monokai");
                    break;
                default:
                    editor.setTheme("ace/theme/github")

            }

        }


        //选择日期
        start_date.datetimepicker({
            format: 'yyyy-mm-dd',
            startView: 'year',
            maxView: 'year',
            minView: 'month',
            autoclose: true,
            pickerPosition: "bottom-right",
            language: 'zh',
        });

        end_date.datetimepicker({
            format: 'yyyy-mm-dd',
            startView: 'year',
            maxView: 'year',
            minView: 'month',
            autoclose: true,
            pickerPosition: "bottom-right",
            language: 'zh',
        });


        //获取日期
        function date_get() {
            var startdate = start_date.val()
            var endate = end_date.val()
            var date_dict = {
                "startdate": startdate,
                "endate": endate
            }
            return date_dict
        }

        //点击运行回测
        function runback_now(stgid) {
            //清除定时器
            clearInterval(period_get)
            //获取编辑器中的策略代码
            var stgcode = editor.getValue()
            var date_ = date_get()
            //登录页面
            loadon()
            $.ajax({
                url: '/stg_opr/',
                type: 'post',
                data: {
                    "stgcode": stgcode,
                    "rundate": JSON.stringify(date_),
                    "stgid": stgid
                },
                success: function (data) {
                    if (data["msg"]) {
                        clearInterval(period_get)
                        var batchid = data['msg']
                        period(stgid, batchid)
                        loadoff()
                    }
                    {#if (data === "y") {#}
                    {#    loadoff()#}
                    {#    period(stgid)#}
                    {# }#}
                },
                error: function () {
                    try {
                    } catch (e) {
                        console.log(e)
                    }
                }
            })
        }

        //收益概览
        function incomeStatistics_get(stgid, batchid) {
            // 获取日期
            var date_obj = date_get()
            $.ajax({
                url: "/detail_income/",
                type: "post",
                data: {
                    "stgid": stgid,
                    "date_obj": JSON.stringify(date_obj),
                    "batchid": batchid
                },
                success: function (result) {
                    if (result != null) {
                        $("#st_date").html(result.start_date);
                        $("#en_date").html(result.end_date);
                        $("#annual_volatility").html(result.annual_volatility);
                        $("#sharpe_ratio").html(result.sharpe_ratio);
                        $("#calmar_ratio").html(result.calmar_ratio);
                        {#$("#omega_ratio").html(result.omega_ratio);#}
                        $("#sortino_ratio").html(result.sortino_ratio);
                        $("#total_return").html(result.total_return + "%");
                        if (result.total_return > 0) {
                            $("#total_return").css("color", "red");
                        } else {
                            $("#total_return").css("color", "green");
                        }
                        $("#annual_return").html(result.annual_return + "%");
                        if (result.annual_return > 0) {
                            $("#annual_return").css("color", "red");
                        } else {
                            $("#annual_return").css("color", "green");
                        }
                        $("#max_draw_down").html(result.max_draw_down + "%");
                        if (result.max_draw_down > 0) {
                            $("#max_draw_down").css("color", "red");
                        } else {
                            $("#max_draw_down").css("color", "green");
                        }
                    } else {
                        $("#annual_return").html('-');
                        $("#annual_volatility").html('-');
                        $("#sharpe_ratio").html('-');
                        $("#calmar_ratio").html('-');
                        $("#stability_of_timeseries").html('-');
                        $("#max_draw_down").html('-');
                        $("#omega_ratio").html('-');
                        $("#sortino_ratio").html('-');
                        $("#annual_return").html('-');
                        $("#start_date").html('-');
                        $("#end_date").html('-');
                    }
                    $(".box-header").css("display", "block")
                },
                error: function () {
                    try {
                    } catch (e) {
                        console.log(e)
                    }
                }
            })
        }

        //净值曲线
        function cumulativereturns_get(stgid, batchid) {
            $("#cumulativereturns").css("background-color", "wheat")
            $.ajax({
                url: "/detail_cumulative/",
                type: "post",
                data: {
                    "stgid": stgid,
                    "batchid": batchid
                },
                success: function (result) {
                    if (result != null) {
                        var myChart = echarts.init(document.getElementById('cumulativereturns'));
                        var option = {
                            tooltip: {
                                trigger: 'axis',
                                formatter: function (obj) {
                                    return obj[0].seriesName + ":" + obj[0].value + '<br>';
                                }
                            },
                            grid: {
                                left: '15%',   // 与容器左侧的距离
                                right: '5%', // 与容器右侧的距离
                                top: '5%',   // 与容器顶部的距离
                                bottom: '22%', // 与容器底部的距离
                            },
                            dataZoom: [
                                {
                                    show: true,
                                    realtime: true,
                                    start: 0,
                                    end: 100
                                },
                                {
                                    type: 'inside',
                                    realtime: true,
                                    start: 0,
                                    end: 100
                                }
                            ],
                            xAxis: {
                                type: 'category',
                                data: null,
                                scale: true
                            },
                            yAxis: {
                                type: 'value',
                                scale: true
                            },
                            series: [{
                                name: '净值',
                                data: null,
                                type: 'line',
                            },
                            ]
                        };
                        option.series[0].data = result.retData;
                        option.xAxis.data = result.retDate;
                        myChart.setOption(option);
                    }
                    $(".box-header").css("display", "block")
                }
            })
        }

        //轮询收益概览和净值曲线
        function period(stgid, batchid) {
            period_get = setInterval(function () {
                incomeStatistics_get(stgid, batchid)
                cumulativereturns_get(stgid, batchid)
            }, 3000)
        }


    </script>
{% endblock %}